package com.banyuan.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/count")
public class CountServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;utf-8");
        Cookie cookie = getCookie(req, "count");
        if (cookie == null) {
            Cookie cookie1 = new Cookie("count",String.valueOf(1));
            resp.addCookie(cookie1);
            resp.getWriter().write("这是你第一次访问");
        } else {
            String value = cookie.getValue();
            int i = Integer.valueOf(value) + 1;
            cookie.setValue(String.valueOf(i));
            resp.addCookie(cookie);
            resp.getWriter().write("这是你第" + i + "次访问");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }


    public Cookie getCookie(HttpServletRequest req,String name) {
        Cookie[] cookies = req.getCookies();
        if (cookies == null || cookies.length < 1) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie;
            }
        }
        return null;
    }
}
